<template>
  <el-dialog fullscreen v-model="dialogVisible" append-to-body @close="dialogClose">
    <el-divider>点检配置</el-divider>
    <div class="transfer-container">
      <!-- 待绑定列表 -->
      <div class="table-container">
        <div class="table-header">待绑定列表</div>
        <el-input v-model="searchQueryLeft" placeholder="请输入点检项进行搜索" clearable />
        <el-table border style="height: 80vh;" ref="leftTable" :data="filteredLeftData" highlight-current-row
          @current-change="handleCurrentChangeLeft" @selection-change="handleSelectionChangeLeft">
          <el-table-column type="selection" width="45" />
          <el-table-column prop="name" label="点检项" min-width="55" />
          <el-table-column prop="description" label="描述" />
        </el-table>
      </div>


      <!-- 控制按钮 -->
      <div class="control-buttons">
        <el-button type="primary" @click="moveToRight" :disabled="!selectedLeft.length > 0" :icon="ArrowRightBold" />
        <el-button type="primary" @click="moveToLeft" :disabled="!selectedRight.length > 0" :icon="ArrowLeftBold" />
      </div>

      <!-- 已绑定列表 -->
      <div class="table-container">
        <div class="table-header">已绑定列表</div>
        <el-input v-model="searchQueryRight" placeholder="请输入点检项进行搜索" clearable />
        <el-table border style="height: 80vh;" highlight-current-row @current-change="handleCurrentChangeRight"
          ref="rightTable" :data="filteredRightData" @selection-change="handleSelectionChangeRight">
          <el-table-column type="selection" width="45" />
          <el-table-column prop="name" label="点检项" min-width="55" />
          <el-table-column prop="description" label="描述" />
        </el-table>
      </div>
    </div>

  </el-dialog>
</template>


<script setup lang="ts">
import { EquipmentKeepSettingApi, EquipmentKeepSetting } from '@/api/business/equipmentkeepsetting'
import { dateFormatter } from '@/utils/formatTime'
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { EquipmentCheckTypeApi, EquipmentCheckType } from '@/api/business/equipmentchecktype'
import { EquipmentCheckConfigApi, EquipmentCheckConfig } from '@/api/business/equipmentcheckconfig'

import {
  ArrowLeftBold,
  ArrowRightBold
} from '@element-plus/icons-vue'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改

// 穿梭框相关数据
const leftData = ref([]) // 待绑定列表
const rightData = ref([]) // 已绑定列表
const searchQueryLeft = ref('') // 左侧搜索框
const searchQueryRight = ref('') // 右侧搜索框
const selectedLeft = ref([]) // 左侧选中的项
const selectedRight = ref([]) // 右侧选中的项

const dialogClose = () => {
  emit('success')
}

const currentRow = ref()
const handleCurrentChangeLeft = (val) => {
  console.log("val.keepSetting", val);
  const ids = val?.keepSetting ? val.keepSetting : []
  getKeepSettingListById(ids)
  currentRow.value = val
}

const handleCurrentChangeRight = (val) => {
  console.log("val.keepSetting", val);
  const ids = val?.keepSetting ? val.keepSetting : []
  getKeepSettingListById(ids)
  currentRow.value = val
}

//保养详细
const keepSettingList = ref([])

//根据id获取保养设置List
const getKeepSettingListById = async (ids) => {
  const res = await EquipmentKeepSettingApi.getEquipmentKeepSettingListByIds(ids);
  keepSettingList.value = res
  console.log("keepSettingList.value", keepSettingList.value);

}

// 获取源数据 初始化已绑定的和未绑定的数据
const getSourceData = async () => {
  try {
    const params = {
      targetId: currentTargetId.value,
      type: currentType.value
    }
    // const res = await EquipmentKeepSettingTypeApi.getEquipmentKeepSettingTypePage(null)
    const res = await EquipmentCheckTypeApi.getEquipmentCheckTypeMapList(params)
    console.log("rrrrrr", res);

    // 处理 unbound（左边：未绑定）
    leftData.value = res.unbound.map(item => ({
      id: item.id,
      name: item.name,
      cycle: item.cycle,
      remind: item.remind,
      ...item
    }))

    // 处理 bind（右边：已绑定）
    rightData.value = res.bind.map(item => ({
      id: item.id,
      name: item.name,
      cycle: item.cycle,
      remind: item.remind,
      ...item
    }))

  } catch (error) {
    console.error("获取待绑定数据失败:", error)
  }
}

// 过滤方法
const filteredLeftData = computed(() => {
  return leftData.value.filter(item =>
    item.name.toLowerCase().includes(searchQueryLeft.value.toLowerCase())
  )
})

const filteredRightData = computed(() => {
  return rightData.value.filter(item =>
    item.name.toLowerCase().includes(searchQueryRight.value.toLowerCase())
  )
})

// 处理选择变化
const handleSelectionChangeLeft = (val) => {
  selectedLeft.value = val
}

const handleSelectionChangeRight = (val) => {
  selectedRight.value = val
}

// 移动到右侧
const moveToRight = async () => {
  selectedLeft.value.forEach(item => {
    const index = leftData.value.indexOf(item)
    if (index > -1) {
      leftData.value.splice(index, 1)
      rightData.value.push(item)
    }
  })

  console.log("移动到右侧的数据", selectedLeft.value);
  const params = {
    type: 'add',
    reqVOList: selectedLeft.value,
    currentType: currentType.value,
    currentTargetId: currentTargetId.value
  }

  await EquipmentCheckConfigApi.batchEquipmentCheckConfig(params)
  message.success("绑定成功!")

  selectedLeft.value = []




}

// 移动到左侧
const moveToLeft = async () => {
  selectedRight.value.forEach(item => {
    const index = rightData.value.indexOf(item)
    if (index > -1) {
      rightData.value.splice(index, 1)
      leftData.value.push(item)
    }
  })

  console.log("移动到左侧的数据", selectedRight.value);
  const params = {
    type: 'delete',
    reqVOList: selectedRight.value,
    currentType: currentType.value,
    currentTargetId: currentTargetId.value
  }
  await EquipmentCheckConfigApi.batchEquipmentCheckConfig(params)
  message.success("解绑成功!")

  selectedRight.value = []

}

//当前类型 按分类或按设备
const currentType = ref()

//分类ID或设备ID
const currentTargetId = ref()


/** 打开弹窗 */
const open = async (type: string, id?: number) => {

  console.log("idddddd", id);


  currentType.value = type
  currentTargetId.value = id

  dialogVisible.value = true
  formType.value = type

  // 打开弹窗时加载数据
  await getSourceData();

  // 如果是修改，设置已选中的值
  if (id) {
    // 这里需要根据实际情况获取已绑定的数据
    // rightData.value = [已绑定的数据]
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  formLoading.value = true
  try {
    // 这里处理提交逻辑，rightData.value 包含已选中的数据
    console.log("已选中的项:", rightData.value)

    // 根据你的业务需求处理提交
    // ...

    message.success(t('common.createSuccess'))
    dialogVisible.value = false
    emit('success')
  } catch (error) {
    console.error("提交失败:", error)
    message.error("操作失败")
  } finally {
    formLoading.value = false
  }
}
</script>


<style scoped>
.transfer-container {
  display: flex;
  justify-content: space-between;
}

.table-container {
  width: 48%;
  border: 1px solid #ebeef5;
  margin-bottom: 20px;
  border-radius: 8px;
  /* 添加圆角：左上、右上、右下、左下都圆角 */

}

.table-header {
  background-color: #409EFF;
  color: white;
  padding: 10px;
  text-align: center;
}

.control-buttons {
  margin-top: 250px;
  margin-left: 50px;
  margin-right: 50px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.control-buttons button {
  margin: 5px 0;
}
</style>
